<?php

namespace App\Http\Middleware;

use App\Models\Manager;
use Closure;
use Illuminate\Support\Facades\Session;

class CheckRegister
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
//        $request->merge(['perfix'=>Session::get('manager.perfix')]);
        $openid = Session::get('wechat.oauth_user.default.original.openid');
        if(Session::get('manager.id')){
            $exist = Manager::where(['id'=>Session::get('manager.id')])->first();
            if(empty($exist))
            {
                return redirect(url(Session::get('manager.perfix').'/register'));
            }
            Session::put('manager.phone', $exist->phone);
            Session::put('manager.name', $exist->name);
            Session::put('manager.id', $exist->id);
            Session::save();
            return $next($request);
        }elseif($openid) {
            $exist = Manager::where(['wx_userinfo->openid'=>$openid])->first();
            if(empty($exist))
            {
                return redirect(url('wx/register'));
            }
            Session::put('manager.phone', $exist->phone);
            Session::put('manager.name', $exist->name);
            Session::put('manager.id', $exist->id);
            Session::save();
            return $next($request);
        }
        else
        {
            if(Session::get('manager.perfix') == 'wx') {
                return redirect(url('wx/register'));
            }else{
                return redirect(url(Session::get('manager.perfix').'/login'));
            }
        }
       /* if(Session::get('manager.id')){
            return $next($request);
        }
        else
        {
            return redirect(url(Session::get('manager.perfix').'/login'));
        }*/

    }
}
